/**
 * @(#)TestOrder.java, 2018/12/27
 * <p/>
 * Copyright 2018 Netease, Inc. All rights reserved.
 * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.chengzhi.netty.http.xml;

import org.jibx.runtime.*;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author 阮承志(wb.ruanchengzhi @ mesg.corp.netease.com)
 **/
public class TestOrder {

    private IBindingFactory factory = null;
    private StringWriter writer = null;
    private StringReader reader = null;
    private final static String CHARSET_NAME = "utf-8";

    private String encode2Xml(Order order) throws JiBXException, IOException {
        factory = BindingDirectory.getFactory(Order.class);
        writer = new StringWriter();
        IMarshallingContext context = factory.createMarshallingContext();
        context.setIndent(2);
        context.marshalDocument(order, CHARSET_NAME, null, writer);
        String xml = writer.toString();
        writer.close();
        System.out.println(xml);
        return xml;
    }

    private Order decode2order(String xml) throws JiBXException {
        reader = new StringReader(xml);
        IUnmarshallingContext context = factory.createUnmarshallingContext();
        Order order = (Order) context.unmarshalDocument(reader);
        return order;
    }

    public static void main(String[] args) throws JiBXException, IOException {
        TestOrder test = new TestOrder();
        Order order = OrderFactory.create(13);
        String body = test.encode2Xml(order);
        Order order1 = test.decode2order(body);
        System.out.println(body + order1);
    }

}
